﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace MN.Framework.Security
{
    public class TokenService
    {
        static string key = DateTime.Now.Hour + "||Mn||{0}||" + DateTime.Now.DayOfYear + "||{1}";
        public static string generateToken(string userName, string hostName)
        {
            var str = string.Format(key, hostName, userName);
            return CryptoService.Encrypt(str.ToLower(), hostName).Replace("=", "___").Replace("?", "_--_").Replace("&", "---").Replace("+", "-__-");
        }
        public static string getUserNameFromToken(string token, string hostName)
        {
            try
            {
                token = token.Replace("___", "=").Replace("_--_", "?").Replace("---", "&").Replace("-__-", "+");
                var baseStr = CryptoService.Decrypt(token, hostName);
                var arr = baseStr.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                return arr[arr.Length - 1];
            }
            catch
            {
                return string.Empty;
            }

        }
        public static bool checkValidationToken(string userName, string hostName, string token)
        {
            CryptoService srvice = new CryptoService();
            var str = string.Format(key, hostName, userName);
            return CryptoService.Encrypt(str.ToLower(), hostName) == token.ToLower();
        }
    }
}
